package com.olocat.cjx.nsims.controller

import com.alibaba.fastjson.JSONObject
import com.olocat.cjx.nsims.pojo.permission.SmsCaptcha
import com.olocat.cjx.nsims.service.UserService
import com.olocat.cjx.nsims.util.Response
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RestController
import javax.annotation.Resource

@RestController
class SettingController {
    @Resource
    lateinit var userService: UserService

    var captcha: Int = 0

    @PostMapping("/api/setting/password")
    fun editPassword(@RequestBody json:JSONObject) : Response {
        println("go in setting password")
        return if ( userService.editPassword(json["id"].toString(),json["old"].toString(),
                json["np"].toString())) {
            Response.builder()
        } else {
            Response.builder(null, 401)
        }
    }

    @PostMapping("api/setting/phone")
    fun editPhone(@RequestBody json:JSONObject) : Response {
        println("go in setting phone")
        return if (json["captcha"].toString() == this.captcha.toString()) {
            userService.updateTelephonById(json["id"].toString(),json["telephone"].toString())
            println("已改手机号码")
            Response.builder()
        } else {
            Response.builder(null,401)
        }
    }

    @PostMapping("api/setting/username")
    fun editUsername(@RequestBody json: JSONObject):Response {
        val id = json["id"].toString()
        val username = json["username"].toString()
        userService.editUsername(id,username)
        return Response.builder()
    }

    @GetMapping("api/setting/captcha")
    fun getCaptcha():Response {
        this.captcha = (Math.random() * 899999 + 100000).toInt()
        println("go in captcha : $captcha")
        return Response.builder(SmsCaptcha(captcha))
    }

    @PostMapping("api/setting/email")
    fun editEmail(@RequestBody json:JSONObject) : Response{
        userService.updateEmailById(json["id"].toString(), json["email"].toString())
        return Response.builder()
    }
}